<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\StoreTagRequest;
use App\Http\Requests\UpdateTagRequest;
use App\Models\Tag;
use Illuminate\Http\Request;

class TagsController extends Controller
{
    /**
     * 标签列表
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = $request->get('query');
        $tags = Tag::search($query)->paginate();

        return view('backend.tags.index', compact('query', 'tags'));
    }

    /**
     * 标签添加页面
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        return view('backend.tags.create');
    }

    /**
     * 标签添加
     *
     * @param  \App\Http\Requests\StoreTagRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(StoreTagRequest $request)
    {
        Tag::create($request->all());

        return redirect()->route('tags.index');
    }

    /**
     * 标签编辑页面
     *
     * @param  integer $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $tag = Tag::findOrFail($id);

        return view('backend.tags.edit', compact('tag'));
    }

    /**
     * 标签编辑
     *
     * @param  integer $id
     * @param  \App\Http\Requests\UpdateTagRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update($id, UpdateTagRequest $request)
    {
        $tag = Tag::with('posts')->findOrFail($id);
        $tag->update($request->all());
        $posts = $tag->posts;

        $posts->each(function ($post) {
            $post->searchable();
        });

        return redirect()->route('tags.index');
    }

    /**
     * 标签删除
     *
     * @param  integer $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($id)
    {
        $tag = Tag::with('posts')->findOrFail($id);
        $posts = $tag->posts;
        $tag->posts()->detach();

        $posts->each(function ($post) {
            $post->searchable();
        });

        $tag->delete();

        return redirect()->route('tags.index');
    }
}
